<?
require_once('functions.php'); 
function GetUsers(){
	$conn = GetConnection();	
	return $results = $conn->query('SELECT * FROM 2012UG_Users');
}

function GetUser($id){
		$conn= GetConnection();
		$sql = "SELECT * FROM 2012UG_Users WHERE id=$id";
		$results = $conn -> query($sql);
		$row = $results -> fetch_assoc();
		$conn->close();
		return $row;
}

function BlankUser(){
	return array('FirstName'=>null, 'LastName'=>null, 'updated_at'=>null, 'Keywords_id'=>null, 'id'=>null);
}

function SaveUser($row){
	$conn = GetConnection();
	$row2 = EscapeRow($row, $conn);
	if(empty($row['id'])){
		$sql = "insert into 2012UG_Users (FirstName, LastName, created_at, updated_at, Keywords_id) "
			.	"Values('$row2[FirstName]', '$row2[LastName]', 'NOW()', 'NOW()', '$row2[Keywords_id]')";
	}
	else{
		$sql = "UPDATE 2012UG_Users "
			.  "Set FirstName='$row2[FirstName]', LastName='$row2[LastName]', created_at='$row2[created_at]', Keywords_id='$row2[Keywords_id]' "
			.  "WHERE id=$row2[id] ";
	}
	$results = $conn -> query($sql);
	$error = $conn ->error;
	$conn->close();
	
	return $error == '' ? true : array('SQL Error' => $error);	
}

function ValidateUser($row){
	$errors = array();
	if(empty($row['FirstName'])) $errors['FirstName'] = 'A first name is required';
	if(empty($row['LastName'])) $errors['FirstName'] = 'A last name is required';
	if(!is_numeric($row['Keywords_id'])) $errors['Keywords_id'] = 'The keyword id must be an number';
	if(empty($row['Keywords_id'])) $errors['Keywords_id'] = 'A keyword id is required';
	
	return count($errors) == 0 ? true : $errors;
	
}
